<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('tiers.dialogTitle')"
    width="90%"
    :close-on-click-modal="false"
    class="tier-levels-dialog"
  >
    <div class="dialog-header">
      <div class="header-badge">
        <Icon icon="mdi:star" class="badge-icon" />
        <span>{{ $t('tiers.standardProduct') }}</span>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <p>{{ $t('tiers.loading') }}</p>
    </div>

    <div v-else-if="tiers.length > 0" class="tiers-grid">
      <div
        v-for="tier in tiers"
        :key="tier.tier"
        class="tier-card"
        :class="{ active: tier.tier === currentUserTier, disabled: !isTierAvailable(tier) }"
      >
        <div class="tier-header">
          <h3 class="tier-name">{{ tier.name }}</h3>
          <div v-if="tier.tier === currentUserTier" class="current-badge">
            <Icon icon="mdi:check-circle" />
            <span>{{ $t('tiers.currentTier') }}</span>
          </div>
        </div>

        <div class="tier-details">
          <div class="detail-item">
            <Icon icon="mdi:calendar-today" class="detail-icon" />
            <div class="detail-content">
              <span class="detail-label">{{ $t('tiers.dailyRate') }}</span>
              <span class="detail-value">{{ formatPercent(tier.dailyRate) }}</span>
            </div>
          </div>

          <div class="detail-item">
            <Icon icon="mdi:calendar-month" class="detail-icon" />
            <div class="detail-content">
              <span class="detail-label">{{ $t('tiers.monthlyRate') }}</span>
              <span class="detail-value">{{ formatPercent(tier.monthlyRate) }}</span>
            </div>
          </div>

          <div class="detail-item highlight">
            <Icon icon="mdi:chart-line" class="detail-icon" />
            <div class="detail-content">
              <span class="detail-label">{{ $t('tiers.annualRate') }}</span>
              <span class="detail-value annual">{{ formatPercent(tier.annualRate) }}</span>
            </div>
          </div>

          <div class="detail-item">
            <Icon icon="mdi:cash-multiple" class="detail-icon" />
            <div class="detail-content">
              <span class="detail-label">{{ $t('tiers.minInvestment') }}</span>
              <span class="detail-value">{{ formatAmount(tier.minInvestment) }} NEAR</span>
            </div>
          </div>
        </div>

        <button
          v-if="!isTierAvailable(tier)"
          class="activate-btn disabled"
          disabled
        >
          {{ $t('tiers.inactive') }}
        </button>
        <button
          v-else-if="tier.tier !== currentUserTier"
          class="activate-btn"
          @click="handleTierActivation(tier)"
        >
          {{ $t('tiers.inactive') }}
        </button>
        <div v-else class="activated-label">
          ✓ {{ $t('tiers.activated') }}
        </div>
      </div>
    </div>

    <div v-else class="no-data">
      <Icon icon="mdi:alert-circle-outline" class="alert-icon" />
      <p>{{ $t('tiers.noData') }}</p>
    </div>

    <template #footer>
      <el-button @click="closeDialog">{{ $t('tiers.close') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Icon } from '@iconify/vue'
import { Loading } from '@element-plus/icons-vue'
import { api } from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

interface TierConfig {
  id: number
  tier: string
  name: string
  dailyRate: number
  monthlyRate: number
  annualRate: number
  minInvestment: number
  isActive: boolean
}

interface Props {
  modelValue: boolean
  currentTier?: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'tier-changed'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  currentTier: 'ENTRY',
})

const emit = defineEmits<Emits>()

const dialogVisible = ref(false)
const loading = ref(false)
const tiers = ref<TierConfig[]>([])
const currentUserTier = ref(props.currentTier)

watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      loadTiers()
    }
  }
)

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emit('update:modelValue', false)
  }
})

watch(
  () => props.currentTier,
  (newVal) => {
    currentUserTier.value = newVal || 'ENTRY'
  }
)

const loadTiers = async () => {
  try {
    loading.value = true
    const response = await api.get('/api/tiers')
    tiers.value = response.data || []

    // 同时获取当前用户等级
    try {
      const userTierRes = await api.get('/api/tiers/my-tier')
      currentUserTier.value = userTierRes.data.currentTier
    } catch (error) {
      console.error('Failed to load user tier:', error)
    }
  } catch (error) {
    console.error('Failed to load tiers:', error)
    ElMessage.error(t('tiers.loadError'))
  } finally {
    loading.value = false
  }
}

const formatPercent = (value: number): string => {
  return (value * 100).toFixed(2) + '%'
}

const formatAmount = (value: number): string => {
  return new Intl.NumberFormat('ko-KR', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value)
}

const isTierAvailable = (tier: TierConfig): boolean => {
  // 所有等级都显示，但只有当前等级激活
  // 可以根据需要添加更多逻辑，例如基于用户的质押金额判断
  return tier.isActive
}

const handleTierActivation = (tier: TierConfig) => {
  // 这里可以添加升级等级的逻辑
  // 目前只是提示，因为等级变更需要管理员操作
  ElMessage.info(t('tiers.contactAdmin'))
}

const closeDialog = () => {
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.tier-levels-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

.dialog-header {
  text-align: center;
  margin-bottom: 32px;

  .header-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px 24px;
    border-radius: 24px;
    font-size: 1.125rem;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

    .badge-icon {
      width: 20px;
      height: 20px;
      color: #fbbf24;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #94a3b8;

  .el-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  p {
    font-size: 1rem;
  }
}

.tiers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.tier-card {
  background: white;
  border: 2px solid #e2e8f0;
  border-radius: 16px;
  padding: 24px;
  transition: all 0.3s ease;
  position: relative;

  &:hover:not(.disabled) {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }

  &.active {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
  }

  &.disabled {
    opacity: 0.6;
    cursor: not-allowed;

    .activate-btn {
      background: #cbd5e1;
      cursor: not-allowed;
    }
  }
}

.tier-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;

  .tier-name {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1a202c;
    margin: 0;
  }

  .current-badge {
    display: flex;
    align-items: center;
    gap: 4px;
    background: #667eea;
    color: white;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 0.875rem;
    font-weight: 600;

    svg {
      width: 16px;
      height: 16px;
    }
  }
}

.tier-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;

  &.highlight {
    background: #fef3c7;
    border: 1px solid #fbbf24;
  }

  .detail-icon {
    width: 24px;
    height: 24px;
    color: #667eea;
    flex-shrink: 0;
  }

  .detail-content {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .detail-label {
      font-size: 0.875rem;
      color: #64748b;
    }

    .detail-value {
      font-size: 1.125rem;
      font-weight: 700;
      color: #1e293b;

      &.annual {
        color: #f59e0b;
        font-size: 1.25rem;
      }
    }
  }
}

.activate-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }

  &.disabled,
  &:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
    transform: none;
  }
}

.activated-label {
  width: 100%;
  padding: 12px;
  background: #10b981;
  color: white;
  border-radius: 8px;
  text-align: center;
  font-size: 1rem;
  font-weight: 600;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
  color: #94a3b8;

  .alert-icon {
    width: 48px;
    height: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    font-size: 1.125rem;
    margin: 0;
  }
}

@media (max-width: 768px) {
  .tiers-grid {
    grid-template-columns: 1fr;
  }

  .tier-card {
    padding: 20px;
  }

  .tier-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .tier-name {
      font-size: 1.25rem;
    }
  }
}
</style>
